//
//  CreateNotifictaionDates.m
//  ClockNotifications
//
//  Created by Anders J.R. Petersen on 26/11/13.
//  Copyright (c) 2013 Anders J.R. Petersen. All rights reserved.
//

#import "CreateNotifictaionDates.h"

static NSMutableArray *dateArray;


@implementation CreateNotifictaionDates

-(NSMutableArray*) getNotifictaionDates: (int) intervalMinutes{
    if(!dateArray){
        dateArray = [[NSMutableArray alloc] init];
    }else{
        [dateArray removeAllObjects];
    }
    
    NSDate *date = [NSDate date];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
    NSInteger h = [components hour];
    NSInteger m = [components minute];
    NSInteger s = [components second];
    
    int secNow      = h*60*60 + m*60 + s;
    int sec9        = 9*60*60;
    int sec21       = 21*60*60;
    int secInterval = 60*intervalMinutes; //15 min minimum interval to cover one day
    
    //today 'dates' : from now untill 21 ( if now is after 9 and before 21)
    int secStartFromDay1    = secNow < sec9  ?   sec9 - secNow    : (secNow > sec21 ? sec21 - secNow : 0  );
    int secEndFromNowDay1   = sec21 - secNow;
    [self addDatesForOneDay: dateArray times: secStartFromDay1 to:secEndFromNowDay1 with:secInterval];
    //tomorrow 'dates' : from 9 tomorrow untill now + 24 hours!
    int secStartFromDay2    = 24*60*60*1 + sec9 - secNow;
    int secEndFromNowDay2   = 24*60*60*1  + secStartFromDay1;
    [self addDatesForOneDay: dateArray times: secStartFromDay2 to:secEndFromNowDay2 with:secInterval];
    
    return dateArray;
}


-(void) addDatesForOneDay: (NSMutableArray*) dateArray times: (int) startTimeFromNowSec to:(int) endTimeFromNowSec with: (int) intervalSec{
    
    int timeSec = startTimeFromNowSec;
    
    while(timeSec < endTimeFromNowSec){
        //only 64 notifications is allowed!!
        if([dateArray count] >= 64) break;
        
        NSDate *date = [NSDate dateWithTimeIntervalSinceNow:timeSec + arc4random_uniform(intervalSec)];
        [dateArray addObject:date];
        timeSec = timeSec + intervalSec;
    }
}

@end
